package com.be.beadmin.product.controller;

import cn.hutool.core.date.DateUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.builder.ExcelWriterBuilder;
import com.be.beadmin.basicData.entity.User;
import com.be.beadmin.common.entity.PageEntity;
import com.be.beadmin.common.exception.BeadminException;
import com.be.beadmin.common.utils.ResultModel;
import com.be.beadmin.design.dto.input.StandFileInfoDto;
import com.be.beadmin.product.dto.input.ErrorReportByWoPage;
import com.be.beadmin.product.dto.input.ErrorReportDto;
import com.be.beadmin.product.dto.input.ErrorReportSimpDto;
import com.be.beadmin.product.dto.output.ErrorPriorityEx;
import com.be.beadmin.product.dto.output.ErrorReportEx;
import com.be.beadmin.product.dto.output.ErrorReportForExportEx;
import com.be.beadmin.product.dto.output.ErrorTypeEx;
import com.be.beadmin.product.entity.ErrorReport;
import com.be.beadmin.product.entity.ErrorReportFileInfo;
import com.be.beadmin.product.repository.ErrorReportFileInfoRepository;
import com.be.beadmin.product.repository.ErrorReportRepository;
import com.be.beadmin.product.service.ErrorReportService;
import com.be.beadmin.project.Util.MinioUtil;
import com.be.beadmin.service.impl.MinioService;
import com.google.common.io.ByteStreams;
import io.minio.MinioClient;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
* @author ljh
* @date 2023-04-21
**/
@Api(tags = {"异常填报"})
@RestController
public class ErrorReportController {

    @Autowired
    private  ErrorReportService errorReportService;




    private String bucketName = "errorreportfile";

    @ApiOperation("异常处理人-获取系统所有用户")
    @PostMapping(value = "/product/getErrorReportMembers")
    public ResultModel getErrorReportMembers()  {
        List<User> userList = errorReportService.getErrorReportMembers();
        return ResultModel.success(userList) ;
    }


    @ApiOperation("获得所有异常优先级")
    @PostMapping("/product/getAllErrorPriority")
    public ResultModel getAllErrorPriority(){
        List<ErrorPriorityEx> errorPriorityDtos = errorReportService.getAllErrorPriority();
        return ResultModel.success(errorPriorityDtos);
    }

    @ApiOperation("获得所有异常类型")
    @PostMapping("/product/getAllErrorType")
    public ResultModel getAllErrorType(){
        List<ErrorTypeEx> errorTypeDtoList = errorReportService.getAllErrorType();
        return ResultModel.success(errorTypeDtoList);
    }

    @ApiOperation("异常全部分页信息")
    @PostMapping(value = "/product/getErrorReportByPage")
    public ResultModel getErrorReportByPage(@RequestBody PageEntity pageEntity)  {
        return ResultModel.success(errorReportService.getErrorReportByPage(pageEntity)) ;
    }

    @ApiOperation("异常分页信息（By Wo工单号）")
    @PostMapping(value = "/product/getErrorReportByPageAndWo")
    public ResultModel getErrorReportByPageAndWo(@RequestBody ErrorReportByWoPage errorReportByWoPage)  {
        return ResultModel.success(errorReportService.getErrorReportByPageAndWo(errorReportByWoPage)) ;
    }

//    @ApiOperation("异常填报（新增）")
//    @PostMapping("/product/addErrorReport")
//    public ResultModel addErrorReport(@RequestBody ErrorReportSimpDto errorReportSimpDto){
//        errorReportService.addErrorReport(errorReportSimpDto);
//        return ResultModel.success(ResultModel.ADD);
//    }

    @ApiOperation("异常填报（新增）可上传附件")
    @PostMapping("/product/addErrorReport2")
    public ResultModel addErrorReport2(@ApiParam(value = "工单id-workOrderInforId") @RequestParam(required = false) String workOrderInforId,
                                       @ApiParam(value = "工单号-wo") @RequestParam(required = false) String Wo,
                                       @ApiParam(value = "生产工序id-taskId") @RequestParam(required = false) String taskId,
                                       @ApiParam(value = "异常分类-errorType",required = true) @RequestParam String errorType,
                                       @ApiParam(value = "异常优先级-priority",required = true) @RequestParam String priority,
                                       @ApiParam(value = "异常处理人-handlingMan",required = true) @RequestParam String handlingMan,
                                       @ApiParam(value = "要求处理时间-deadLine",required = true) @RequestParam String deadLine,
                                       @ApiParam(value = "异常描述-errorDes") @RequestParam(required = false) String errorDes,
                                       @ApiParam(value = "异常填报人-operator",required = true) @RequestParam String operator,
                                       @ApiParam(value = "异常附件上传") @RequestParam(required = false,value="file") MultipartFile[] multipartFiles,
                                       @ApiParam(value = "项目名称") @RequestParam(required = false) String projectName,
                                       @ApiParam(value = "工时") @RequestParam(required = false) Float workHour
                                       ) throws Exception {

        try {
            errorReportService.addErrorReport2(workOrderInforId,Wo,taskId,errorType,priority,handlingMan, DateUtil.parse(deadLine),errorDes,operator,multipartFiles,bucketName,projectName,workHour);
            return ResultModel.success(ResultModel.ADD);
        } catch (BeadminException e) {
            return ResultModel.error(-1,e.getMessage());
        } catch (Exception e) {
            return ResultModel.error(-2,e.getMessage());
        }
    }


    @ApiOperation("异常处理（不能处理，变更处理人）")
    @PostMapping("/product/deliverErrorReport")
    public ResultModel deliverErrorReport(@RequestBody ErrorReportDto errorReportDto){
        errorReportService.deliverErrorReport(errorReportDto);
        return ResultModel.success(ResultModel.UPDATE);
    }

    @ApiOperation("异常处理（能够处理）")
    @PostMapping("/product/updateErrorReport")
    public ResultModel updateErrorReport(@RequestBody ErrorReportDto errorReportDto){
        errorReportService.updateErrorReport(errorReportDto);
        return ResultModel.success(ResultModel.UPDATE);
    }

    @ApiOperation("完成异常处理（进入完成tab）")
    @PostMapping("/product/finishErrorReport")
    public ResultModel finishErrorReport(@RequestBody ErrorReportDto errorReportDto){
        errorReportService.finishErrorReport(errorReportDto.getId());
        return ResultModel.success(ResultModel.DELETE);
    }

    @PostMapping("/product/delErrorReport")
    public ResultModel delErrorReport(@RequestBody ErrorReportDto errorReportDto){
        errorReportService.delErrorReport(errorReportDto.getId());
        return ResultModel.success(ResultModel.DELETE);
    }

    @ApiOperation("导出（根据处理状态）")
    @PostMapping("/product/exportErrorReportByHandleStatus")
    public void exportErrorReportByHandleStatus(HttpServletResponse response ,
                                  @ApiParam(value = "处理状态", required = true) @RequestParam Integer handleStatus) throws IOException {

        List<ErrorReportForExportEx> errorReportExes = errorReportService.exportErrorReportByHandleStatus(handleStatus);
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("异常导出", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        //EasyExcel.write(response.getOutputStream(), ErrorReportForExportEx.class).sheet("sheet1").doWrite(errorReportExes);
        ExcelWriterBuilder ewb=EasyExcel.write(response.getOutputStream(), ErrorReportForExportEx.class);
        ewb.excelType(ExcelTypeEnum.XLS);
        ewb.sheet("sheet1").doWrite(errorReportExes);
    }

    @ApiOperation("导出(全部)")
    @PostMapping("/product/exportErrorReport")
    public void exportErrorReport(HttpServletResponse response) throws IOException {

        List<ErrorReportForExportEx> errorReportExes = errorReportService.exportAllErrorReport();
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("ErrorReport接口", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        //EasyExcel.write(response.getOutputStream(), ErrorReportForExportEx.class).sheet("sheet1").doWrite(errorReportExes);
        ExcelWriterBuilder ewb=EasyExcel.write(response.getOutputStream(), ErrorReportForExportEx.class);
        ewb.excelType(ExcelTypeEnum.XLS);
        ewb.sheet("sheet1").doWrite(errorReportExes);
    }


    @ApiOperation("获取异常处理")
    @PostMapping("/product/getErrorReportProgress")
    public ResultModel getErrorReportProgress(){
        ArrayList<Integer> errorReportProgress = new ArrayList<>();
        errorReportProgress = errorReportService.getErrorReportProgress();
        return ResultModel.success(errorReportProgress);
    }
}